import { Form } from 'antd';
import { useEffect, useState, useRef, useCallback } from 'react';

import workbenchService from '@/api/services/workbenchService';
import { SimpleEditableSelect, Select, CustomFormLabel } from '@/components/eai-design';
import TipsModals from '@/components/modals/TipsModals';
import useModal from '@/hooks/use-modal/useModal';
import { useUserInfo } from '@/store/userStore';

import styles from './index.module.scss';

interface AppTagSelectProps {
  value?: string;
  // 标签变化回调
  tagChange?: (data: string) => void;
  // 样式类名
  className?: string;
  // 是否需要添加标签
  needAdd?: boolean;
}
interface TagParams {
  tag: string;
}

// 缓存机制，避免重复请求
let tagListCache: Array<{ label: string; value: string; id: string }> | null = null;
let lastFetchTime = 0;
const CACHE_DURATION = 5000; // 5秒缓存时间
let ongoingRequest: Promise<any> | null = null;
export default function AppTagSelect({
  value,
  tagChange = () => {},
  className,
  needAdd = false,
}: AppTagSelectProps) {
  const { role } = useUserInfo();

  const [form] = Form.useForm<TagParams>();
  const modal = useModal('delete');

  // 状态管理
  const [selectedTags, setSelectedTags] = useState<string>(value || '全部标签');
  const [tagList, setTagList] = useState<Array<{ label: string; value: string; id: string }>>([]);
  const [tagsLoading, setTagsLoading] = useState(false);
  const [deleteData, setDeleteData] = useState<{ label: string; value: string; id: string } | null>(
    null,
  );
  const deleteResolveRef = useRef<((value: boolean) => void) | null>(null);

  // 当value属性变化时，更新表单值
  useEffect(() => {
    if (needAdd && value !== undefined) {
      form.setFieldsValue({ tag: value });
    } else if (!needAdd && value !== undefined) {
      // 当不需要添加功能时，更新selectedTags状态
      setSelectedTags(value || '全部标签');
    }
  }, [value, needAdd, form]);

  const handleTagChange = (value: string) => {
    setSelectedTags(value);
    tagChange(value);
  };

  const handleTagOptionsChange = async (
    options: { label: string; value: string; id?: string }[],
    type: 'add' | 'delete',
  ): Promise<boolean> => {
    console.log('options', options, type);

    // newOptions和tagOptions比较，获取新增的选项和删除的选项
    const addOptions = options.filter((option) => !tagList.some((t) => t.value === option.value));
    const deleteOptions = tagList.filter(
      (option) => !options.some((t) => t.value === option.value),
    );
    const option =
      type === 'add' ? addOptions[addOptions.length - 1] : deleteOptions[deleteOptions.length - 1];

    // 如果是删除操作，先显示确认弹窗
    if (type === 'delete') {
      // 确保删除的选项有id属性
      if (option && option.id) {
        setDeleteData(option as { label: string; value: string; id: string });
        modal.delete.open();
      } else {
        console.error('删除的选项缺少id属性');
        return false;
      }

      // 返回一个Promise，等待用户确认删除结果
      return new Promise((resolve) => {
        deleteResolveRef.current = resolve;
      });
    }

    // 添加操作保持原有逻辑
    const res = await workbenchService.addAppTag({
      name: option.label,
      sort_order: options.length + 1,
    });
    if (res) {
      setTagList([...tagList, { label: res.name, value: res.name, id: res.id }]);
      // 清除缓存，确保数据一致性
      tagListCache = null;
      // 添加标签成功后重新获取标签列表，确保数据同步
      fetchTags();
      // 触发标签更新事件，通知其他组件
      window.dispatchEvent(new CustomEvent('appTagUpdated'));
      return true;
    }

    return false;
  };

  const onDeleteModel = async () => {
    if (deleteData) {
      try {
        console.log('deleteData.id', deleteData.id);
        const res = await workbenchService.delAppTag(deleteData.id ?? '');

        if (res) {
          // 获取当前表单中的值
          const currentValue = form.getFieldValue('tag');
          // 如果删除的标签正好是当前选中的标签，清空表单值
          if (currentValue === deleteData.value) {
            form.setFieldsValue({ tag: undefined });
            // 触发onChange回调，通知父组件值已清空
            tagChange('');
          }

          // 清除缓存，确保数据一致性
          tagListCache = null;
          // 删除成功后重新获取标签列表，确保数据同步
          fetchTags();
          // 触发标签更新事件，通知其他组件
          window.dispatchEvent(new CustomEvent('appTagUpdated'));

          modal.delete.close();
          // 通知SimpleEditableSelect组件删除成功
          if (deleteResolveRef.current) {
            deleteResolveRef.current(true);
            deleteResolveRef.current = null;
          }
        } else if (deleteResolveRef.current) {
          // 删除失败时通知组件
          deleteResolveRef.current(false);
          deleteResolveRef.current = null;
        }
      } catch (error) {
        console.error('删除标签失败:', error);
        // 删除失败时通知组件
        if (deleteResolveRef.current) {
          deleteResolveRef.current(false);
          deleteResolveRef.current = null;
        }
      }
    }
  };

  // 获取标签列表的函数（带缓存和防重复请求）
  const fetchTags = useCallback(async () => {
    // 只有管理员才获取标签
    if (role?.code === 'super_admin' || role?.code === 'admin') {
      const now = Date.now();

      // 检查缓存是否有效
      if (tagListCache && now - lastFetchTime < CACHE_DURATION) {
        setTagList(tagListCache);
        return;
      }

      // 如果已有正在进行的请求，等待其完成
      if (ongoingRequest) {
        try {
          await ongoingRequest;
          if (tagListCache) {
            setTagList(tagListCache);
          }
        } catch (error) {
          console.error('等待请求完成时出错:', error);
        }
        return;
      }

      setTagsLoading(true);

      // 创建新的请求
      ongoingRequest = workbenchService.getAppTagList();

      try {
        const res = await ongoingRequest;
        const tags = res.tags || [];

        // 将标签数据转换为需要的格式
        const formattedTags = tags.map((tag: { name: string; id: string }) => ({
          label: tag.name,
          value: tag.name,
          id: tag.id,
        }));

        // 更新缓存
        tagListCache = formattedTags;
        lastFetchTime = now;

        setTagList(formattedTags);
      } catch (error) {
        console.error('获取标签失败:', error);
        setTagList([]);
      } finally {
        setTagsLoading(false);
        ongoingRequest = null;
      }
    }
  }, [role]); // 添加role作为依赖项，确保角色变化时重新获取标签

  // 初始化获取标签
  useEffect(() => {
    fetchTags();
  }, [role, fetchTags]); // 当角色变化时重新获取

  // 监听标签更新事件（添加防抖避免重复请求）
  useEffect(() => {
    let debounceTimer: NodeJS.Timeout;

    const handleTagUpdate = () => {
      // 清除之前的定时器
      clearTimeout(debounceTimer);
      // 设置新的定时器，300ms后执行
      debounceTimer = setTimeout(() => {
        fetchTags();
      }, 300);
    };

    window.addEventListener('appTagUpdated', handleTagUpdate);
    return () => {
      window.removeEventListener('appTagUpdated', handleTagUpdate);
      clearTimeout(debounceTimer);
    };
  }, [fetchTags]); // 添加 fetchTags 作为依赖项，确保事件监听器能够访问最新的 fetchTags 函数

  return needAdd ? (
    <>
      <Form form={form} layout="vertical" className="relative">
        <Form.Item
          name="tag"
          label={
            <CustomFormLabel prefix description="设置智能体应用的应用类别">
              应用类型
            </CustomFormLabel>
          }
          // rules={[
          //   {
          //     required: true,
          //     message: '请选择应用类型',
          //   },
          // ]}
          required={false}
        >
          <SimpleEditableSelect
            // value={value}
            className=" w-full"
            onChange={(e) => {
              tagChange(e);
            }}
            showSearch
            options={tagList}
            placeholder="请选择类型"
            onOptionsChange={handleTagOptionsChange}
            allowAdd
            maxLength={20}
            addButtonText="添加类型"
          />
        </Form.Item>
      </Form>
      <TipsModals
        open={modal.delete.isOpen}
        onOk={onDeleteModel}
        confirmLoading={modal.delete.isLoading}
        onCancel={() => {
          modal.delete.close();
          // 用户取消删除时，清空resolve引用但不调用，让Promise保持pending状态
          deleteResolveRef.current = null;
        }}
        okText="确定"
        cancelText="取消"
      >
        <div className="text-[14px] leading-[22px] text-text-4">
          该标签删除后，相关应用将会变成无标签状态
        </div>
      </TipsModals>
    </>
  ) : (
    <Select
      className={className}
      loading={tagsLoading}
      value={value || selectedTags}
      options={[{ label: '全部标签', value: '全部标签' }, ...tagList]}
      defaultValue="全部标签"
      showSearch
      dropdownClassName={styles.customSelectDropdown}
      onChange={(value) => {
        handleTagChange(value);
      }}
    />
  );
}
